<template>
  <div class="requirement-children-tab">
    <div class="tab-header">
      <div class="header-info">
        <span class="item-count">子需求（{{ children.length }}）</span>
      </div>
      <div class="header-actions">
        <el-button
          type="primary"
          size="small"
          @click="handleCreateChild"
        >
          <el-icon><Plus /></el-icon>
          新建子需求
        </el-button>
      </div>
    </div>

    <div v-loading="loading" class="children-list">
      <el-table
        v-if="children.length > 0"
        :data="children"
        size="default"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="title" label="需求标题" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <el-link
              type="primary"
              @click="handleViewChild(row.id)"
              :underline="false"
            >
              {{ row.title }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag
              :type="getStatusType(row.status)"
              size="small"
            >
              {{ getStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="90">
          <template #default="{ row }">
            <el-tag
              :type="getPriorityType(row.priority)"
              size="small"
            >
              {{ getPriorityName(row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="负责人" width="150" show-overflow-tooltip>
          <template #default="{ row }">
            <UserDisplay
              :user-id="row.assignee_id"
              :user-name="row.assignee_name"
              :show-avatar="true"
              size="small"
            />
          </template>
        </el-table-column>
        <el-table-column label="报告人" width="150" show-overflow-tooltip>
          <template #default="{ row }">
            <UserDisplay
              :user-id="row.reporter_id"
              :user-name="row.reporter_name"
              :show-avatar="true"
              size="small"
            />
          </template>
        </el-table-column>
        <el-table-column prop="children_count" label="子需求数" width="90" align="center">
          <template #default="{ row }">
            <span v-if="row.children_count > 0" class="children-count">{{ row.children_count }}</span>
            <span v-else class="no-children">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="110">
          <template #default="{ row }">
            {{ formatDate(row.created_at) || '—' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              size="small"
              @click="handleViewChild(row.id)"
            >
              查看
            </el-button>
            <el-button
              link
              type="danger"
              size="small"
              @click="handleDeleteChild(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-empty v-else description="暂无子需求，点击“新建子需求”添加" :image-size="80" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { RequirementResponse } from '@/api/requirements'
import { getRequirements, deleteRequirement } from '@/api/requirements'
import { formatDate } from '@/utils/date'
import UserDisplay from '@/components/ui/UserDisplay.vue'

interface Props {
  requirementId: string
  projectId?: string
  statusOptions: Array<{ value: string; label: string; color?: string }>
  priorityOptions: Array<{ value: string; label: string; color?: string }>
}

const props = defineProps<Props>()

const emit = defineEmits<{
  (e: 'create-child', requirementId: string): void
  (e: 'view-child', requirementId: string): void
  (e: 'child-updated'): void
}>()

const loading = ref(false)
const children = ref<RequirementResponse[]>([])

// 加载子需求
const loadChildren = async () => {
  if (!props.requirementId) {
    children.value = []
    return
  }

  loading.value = true
  try {
    const response = await getRequirements({
      parent_id: props.requirementId,
      size: 100
    })
    
    if (response.success && response.data) {
      children.value = response.data as RequirementResponse[]
    } else {
      children.value = []
    }
  } catch (error) {
    console.error('加载子需求失败:', error)
    ElMessage.error('加载子需求失败')
    children.value = []
  } finally {
    loading.value = false
  }
}

// 查看子需求
const handleViewChild = (childId: string) => {
  emit('view-child', childId)
}

// 新建子需求
const handleCreateChild = () => {
  emit('create-child', props.requirementId)
}

// 删除子需求
const handleDeleteChild = async (child: RequirementResponse) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除子需求"${child.title}"吗？删除后无法恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    try {
      const response = await deleteRequirement(child.id)
      if (response.success) {
        ElMessage.success('删除成功')
        await loadChildren()
        emit('child-updated')
      } else {
        ElMessage.error(response.message || '删除失败')
      }
    } catch (error) {
      console.error('删除子需求失败:', error)
      ElMessage.error('删除子需求失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除子需求失败:', error)
    }
  }
}

// 状态辅助函数
function getStatusType(status?: string): 'info' | 'success' | 'warning' | 'danger' {
  if (!status) return 'info'
  const option = props.statusOptions.find(item => item.value === status)
  if (!option?.color) return 'info'
  const colorMap: Record<string, 'info' | 'success' | 'warning' | 'danger'> = {
    '#909399': 'info',
    '#409EFF': 'info',
    '#67C23A': 'success',
    '#E6A23C': 'warning',
    '#F56C6C': 'danger'
  }
  return colorMap[option.color] ?? 'info'
}

function getStatusName(status?: string): string {
  if (!status) return ''
  const option = props.statusOptions.find(item => item.value === status)
  return option?.label || status
}

// 优先级辅助函数
function getPriorityType(priority?: string): 'info' | 'success' | 'warning' | 'danger' {
  if (!priority) return 'info'
  const option = props.priorityOptions.find(item => item.value === priority)
  if (!option?.color) return 'info'
  const colorMap: Record<string, 'info' | 'success' | 'warning' | 'danger'> = {
    '#909399': 'info',
    '#409EFF': 'info',
    '#67C23A': 'success',
    '#E6A23C': 'warning',
    '#F56C6C': 'danger'
  }
  return colorMap[option.color] ?? 'info'
}

function getPriorityName(priority?: string): string {
  if (!priority) return ''
  const option = props.priorityOptions.find(item => item.value === priority)
  return option?.label || priority
}

// 监听需求ID变化
watch(() => props.requirementId, (newId) => {
  if (newId) {
    loadChildren()
  } else {
    children.value = []
  }
}, { immediate: true })

onMounted(() => {
  if (props.requirementId) {
    loadChildren()
  }
})
</script>

<style scoped lang="scss">
.requirement-children-tab {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 16px;
}

.tab-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 12px;
  border-bottom: 1px solid #ebeef5;

  .header-info {
    .item-count {
      font-size: 15px;
      font-weight: 600;
      color: #303133;
    }
  }

  .header-actions {
    display: flex;
    gap: 8px;
  }
}

.children-list {
  min-height: 300px;
}

.children-count {
  color: #409eff;
  font-weight: 500;
}

.no-children {
  color: #909399;
}
</style>

